package com.leetcode.LeetCode精选TOP面试题;

import java.util.Arrays;

/**
 * @author 覃国强
 * @date 2022-07-16 13:06
 */
public class 题库_0238_除自身以外数组的乘积 {

  public static void main(String[] args) {
    System.out.println(Arrays.toString(new Solution().productExceptSelf(new int[]{1, 2, 3, 4})));
  }

  static
  class Solution {
    public int[] productExceptSelf(int[] nums) {
      int[] answer = new int[nums.length];

      // 前缀积
      int product = 1;
      for (int i = 0; i < nums.length; ++i) {
        product *= nums[i];
        answer[i] = product;
      }

      // 后缀积
      product = 1;
      for (int i = nums.length - 1; i > 0; --i) {
        answer[i] = product * answer[i - 1];
        product *= nums[i];
      }

      answer[0] = product;

      return answer;
    }
  }

}
